package controllers;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entities.Logins;
import entities.Persons;
import entities.Users;

/**
 * Servlet implementation class LoginControllerServlet
 */
public class LoginControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	// @EJB
	// private UsersFacadeREST userFacade;
	String mysJDBCDriver = "com.mysql.jdbc.Driver";
	String mysURL = "jdbc:mysql://" + MainControllerServlet.DB_URL;
	String mysUserID = MainControllerServlet.DB_ID;
	String mysPassword = MainControllerServlet.DB_PW;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginControllerServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		System.out.println("LoginControllerServlet.doPost");
		System.out.println("request.getParameterMap(): "
				+ request.getParameterMap());
		System.out.println("request.getAttributeNames(): "
				+ request.getAttributeNames().nextElement());
		if (request.getParameter("action") != null) {
			String actionStr = request.getParameter("action").trim();
			System.out.println("param.action: " + actionStr);
			if (actionStr.equals("logout")) {
				// session.setAttribute("login", ""); //Instead of
				// setAttribute() which is deprecated.
				response.sendRedirect("/");
				return;
			} else if (actionStr.equals("userLogin")) {
				processRequestLogin(request, response);
			} else if (actionStr.equals("userRegistration")) {
				processRequestRegister(request, response);
			}

		} else {
			System.out
					.println("LoginControllerServlet.doPost ends - request error - getParameter failed");
		}
	}

	private void processRequestLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();

		String userId = request.getParameter("username");
		String password = request.getParameter("userpasswd");

		session.setAttribute("login", "");
		if ((userId != null) && (password != null)) {
			if (userId.trim().equals("") || password.trim().equals("")) {
				response.sendRedirect("index.jsp");
			} else {
				// code start here
				java.sql.Connection conn = null;
				try {
					Class.forName(mysJDBCDriver).newInstance();
					java.util.Properties sysprops = System.getProperties();
					sysprops.put("user", mysUserID);
					sysprops.put("password", mysPassword);

					// connect to the database
					conn = java.sql.DriverManager.getConnection(mysURL,
							sysprops);
					System.out
							.println("Connected successfully to database using JConnect");

					// controllers.UsersJpaController user = new
					// UsersJpaController(null, null)
					// Querying.
					conn.setAutoCommit(false);
					String queryStr = " SELECT * " + "FROM `jihhwang`.`logins`"
							+ "WHERE id='" + userId + "' " + "AND pw='"
							+ password + "';";
					java.sql.Statement stmt1 = conn.createStatement();
					java.sql.ResultSet rs = stmt1.executeQuery(queryStr);
					if (rs.next()) {
						synchronized (session) {
							// login success
							session.setAttribute("login", userId);
							session.setAttribute("id", rs.getObject("id"));
							session.setAttribute("msg",
									"Welcome : " + rs.getObject("id"));

							response.sendRedirect("index.jsp");
							// RequestDispatcher view =
							// request.getRequestDispatcher("index.jsp");
							// view.forward(request, response);
						}

					} // else {
						// rs = stmt1
						// .executeQuery(" SELECT * FROM Professor where Id='"
						// + username
						// + "' and Pswd='"
						// + userpasswd + "'");
						// if (rs.next()) {
						// session.setAttribute("login", username);
						// response.sendRedirect("FacultyInformation.jsp");
						// }
					else {
						// username or password mistake
						// response.sendRedirect("passMistake.jsp");

						// login failed
						// session.setAttribute("login", );
						// session.setAttribute("user_id",
						// rs.getObject("user_id"));
						session.setAttribute("msg", "Login failed");

						response.sendRedirect("index.jsp");
						// RequestDispatcher view =
						// request.getRequestDispatcher("index.jsp");
						// view.forward(request, response);
					}

				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						conn.close();
					} catch (Exception ee) {
						ee.printStackTrace();
					}
					;
				} // end of try
			}// end of connection & querying
		} else {
			System.out.println("id or password error");
		}

	}

	private void processRequestRegister(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("LoginControllerServlet.processRequestRegister");

		HttpSession session = request.getSession();

		// userFacade = new UsersFacadeREST();

		// UsersFacadeREST usersFacade = new UsersFacadeREST();
		// PersonsFacadeREST personsFacade = new PersonsFacadeREST();
		// LoginsFacadeREST loginsFacade = new LoginsFacadeREST();
		//
		// EntityManager usersEntityManager = usersFacade.getEntityManager();
		// EntityManager personsEntityManager =
		// personsFacade.getEntityManager();
		//
		// UsersJpaController usersJpaController = new UsersJpaController();
		// PersonsJpaController personsJpaController = new
		// PersonsJpaController();

		// Persons person = new Persons();
		// Users user = new Users();
		// Logins login = new Logins();
		//
		// personsEntityManager= personsJpaController.getEntityManager();
		//
		// try {
		// String ssn = request.getParameter("ssn").trim();
		// if (personsFacade.find(ssn) == null) // find duplicate
		// {
		// System.out.println("SSN is duplicated");
		// } else {
		//
		// person.setSsn(Integer.valueOf(ssn));
		// person.setLastName(request.getParameter("lastName").trim());
		// person.setFirstName(request.getParameter("firstName").trim());
		// person.setSex(request.getParameter("sex").trim());
		// person.setAddress(request.getParameter("address").trim());
		// person.setCity(request.getParameter("city").trim());
		// person.setState(request.getParameter("state").trim());
		// person.setZipCode(Integer.valueOf(request.getParameter("zipCode").trim()));
		// person.setEmailAddress(request.getParameter("emailAddress").trim());
		// person.setTelephone(request.getParameter("telephone").trim());
		// int year = Integer.valueOf(request.getParameter("year").trim());
		// int month = Integer.valueOf(request.getParameter("month").trim());
		// int day = Integer.valueOf(request.getParameter("day").trim());
		// person.setDateOfBirth(new Date(year, month, day));
		// personsFacade.create(person);
		//
		// user.setSsn(person);
		// usersFacade.create(user);
		//
		// login.setId(request.getParameter("id").trim());
		// login.setPw(request.getParameter("pw1").trim());
		// login.setUserId(user);
		// loginsFacade.create(login);
		//
		// usersEntityManager.flush();
		// personsEntityManager.flush();
		// System.out.println("new person, user, login created");
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// personsEntityManager.
		// personsFacade.create();

		// code start here
		Accessdb db = new Accessdb();
		java.sql.Connection conn = db.getConnection();
		System.out.println("Connected successfully to database using JConnect");
		// controllers.UsersJpaController user = new UsersJpaController(null,
		// null)
		// Querying.

		Persons person = new Persons();
		Users user = new Users();
		Logins login = new Logins();

		try {
			conn.setAutoCommit(false);
			String ssnStr = request.getParameter("ssn");

			// if (ssn == null) // find duplicate
			// {
			// System.out.println("SSN is duplicated");
			// } else if (db.findPersonBySsn(ssn)) {
			// System.out.println("Same person with ssn : " + ssn);
			// }

			// person.setSsn(Integer.valueOf(ssn));
			// person.setLastName(request.getParameter("lastName").trim());
			// person.setFirstName(request.getParameter("firstName").trim());
			// person.setSex(request.getParameter("sex").trim());
			// person.setAddress(request.getParameter("address").trim());
			// person.setCity(request.getParameter("city").trim());
			// person.setState(request.getParameter("state").trim());
			// person.setZipCode(Integer.valueOf(request.getParameter("zipCode")
			// .trim()));
			// person.setEmailAddress(request.getParameter("emailAddress").trim());
			// person.setTelephone(request.getParameter("telephone").trim());
			// int year = Integer.valueOf(request.getParameter("year").trim());
			// int month =
			// Integer.valueOf(request.getParameter("month").trim());
			// int day = Integer.valueOf(request.getParameter("day").trim());
			// person.setDateOfBirth(new Date(year, month, day));
			// personsFacade.create(person);
			Integer ssn = Integer.valueOf(ssnStr);
			String lastName = request.getParameter("lastName").trim();
			String firstName = request.getParameter("firstName").trim();
			String sex = request.getParameter("sex").trim();
			String address = request.getParameter("address").trim();
			String city = request.getParameter("city").trim();
			String state = request.getParameter("state").trim();
			String zipCode = request.getParameter("zipCode").trim();
			String emailAddress = request.getParameter("emailAddress").trim();
			String telephone = request.getParameter("telephone").trim();
			int year = Integer.valueOf(request.getParameter("year").trim());
			int month = Integer.valueOf(request.getParameter("month").trim());
			int day = Integer.valueOf(request.getParameter("day").trim());
			Date dateOfBirth = new Date(year, month, day);
			
			db.insertPerson(ssn, lastName, firstName, sex, address, city, state, zipCode, telephone, emailAddress, dateOfBirth); 

			user.setSsn(person);
			// usersFacade.create(user);
			db.insertUser(ssn, 0);

			login.setId(request.getParameter("id").trim());
			login.setPw(request.getParameter("pw1").trim());
			login.setUserId(user);
			// loginsFacade.create(login);

			System.out.println("new person, user, login created");

			// db.insertUserPerson(ssn, lastName, firstName, sex, address, city,
			// state, zipCode, telephone, emailAddress, dateOfBirth, rating);
			// db.insertPerson(person);
			// db.insertUser(user);
			// db.insertLogin(login);

			// RequestDispatcher view =
			// request.getRequestDispatcher("index.jsp");
			// view.forward(request, response);
			response.sendRedirect("index.jsp");
			// if ((userId != null) && (password != null)) {
			// if (userId.trim().equals("") || password.trim().equals("")) {
			// session.setAttribute("login", "success");
			// response.sendRedirect("index.jsp");
			// } else {
			// }
			// }
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("registration error");
			request.setAttribute("msg", "Registration Error!");
		} finally {
			try {
				conn.close();
			} catch (Exception ee) {
				ee.printStackTrace();
			}
			;
		}
		db.closeConnection(conn);
		// end of try
		response.sendRedirect("index.jsp");
	}// end of connection & querying

}